package article

import (
	"errors"
	"go-demo/core/db"
	"gorm.io/gorm"
)

type Article struct {
	Id         int    `json:"id"`
	CategoryId int    `json:"category_id"`
	Title      string `json:"title"`
	Content    string `json:"content"`
	Keywords   string `json:"keywords"`
	Author     string `json:"author"`
	Sort       int    `json:"sort"`
	Views      int    `json:"views"`
	Status     int    `json:"status"`
	CreateTime int    `json:"create_time"`
	UpdateTime int    `json:"update_time"`
	DeleteTime int    `json:"delete_time"`
}

func (Article) TableName() string {
	return "demo_article"
}

func FindById(id int) Article {
	article := Article{}
	db.DB.Model(&article).Select("demo_article.*,demo_category.name as category_name").
		Joins("left join demo_category on demo_article.category_id = demo.category.id").
		Where("demo_article.id = ?", id).
		Find(&article)
	return article
}

func CheckIsExist(id int) (article Article, err error) {
	result := db.DB.Model(&article).Select("demo_article.*,demo_category.name as category_name").
		Joins("left join demo_category on demo_article.category_id = demo.category.id").
		Where("demo_article.id = ?", id).
		Find(&article)
	if errors.Is(result.Error, gorm.ErrRecordNotFound) {
		err = errors.New("数据不存在")
		return
	}
	return
}
